<template>
  <el-dialog
    v-model="dialogVisible"
    title="分配权限"
    width="600px"
  >
    <el-tree
      ref="permissionTreeRef"
      :data="permissions"
      show-checkbox
      node-key="id"
      default-expand-all
      :props="defaultProps"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定分配
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoleFormActions} from '@/services/auth/roles/rolesApiServices';


const dialogVisible = ref(false);
const permissionTreeRef = ref();
const permissions = ref([]);
const defaultProps = {
  children: 'children',
  label: 'name'
};

const roleId = ref(null);

// 使用 useRoleFormActions 中的 assignMenuToRole
const { assignPermissionToRole } = useRoleFormActions({
  onRoleChange: () => {
    // 这里可以添加刷新逻辑，如果需要
  }
});

// 获取和设置权限数据的方法
const setPermissionData = (permissionData) => {
  permissions.value = permissionData;
};

// 显示对话框的方法
const showAssignPermissionDialog = (id) => {
  roleId.value = id;
  dialogVisible.value = true;
};

// 提交分配
const handleSubmit = async () => {
  try {
    const selectedPermissions = permissionTreeRef.value.getCheckedKeys();
    await assignPermissionToRole(roleId.value, selectedPermissions);
    ElMessage.success('权限分配成功');
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('权限分配失败');
  }
};

// 暴露方法给父组件
defineExpose({
  showAssignPermissionDialog,
  setPermissionData
});
</script>